package com.nbufe.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nbufe.domain.entity.EmissionOrigin;
import com.nbufe.domain.entity.Process;
import com.nbufe.enums.AppHttpCodeEnum;
import com.nbufe.exception.SystemException;
import com.nbufe.mapper.EmissionOriginMapper;
import com.nbufe.mapper.ProcessMapper;
import com.nbufe.service.EmissionOriginService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * (EmissionOrigin)表服务实现类
 *
 * @author luzhiheng
 * @since 2023-12-26 16:01:11
 */
@Service("emissionOriginService")
public class EmissionOriginServiceImpl extends ServiceImpl<EmissionOriginMapper, EmissionOrigin> implements EmissionOriginService {

    @Resource
    private ProcessMapper processMapper;

    @Transactional
    @Override
    public void deleteByProcessIdAndEmissionId(Long processId, Long emissionId) {
        // 删除工序能源关系
        Process process = processMapper.selectById(processId);
        if (process == null) {
            throw new SystemException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        List<Long> emissionOriginIds = JSON.parseArray(process.getEmissionOrigin(), Long.class);
        emissionOriginIds = emissionOriginIds.stream().filter(i -> !i.equals(emissionId)).collect(Collectors.toList());
        process.setEmissionOrigin(JSON.toJSONString(emissionOriginIds));
        processMapper.updateById(process);

        // 删除能源物质
        this.removeById(emissionId);
    }
}

